import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {nanoid} from 'nanoid'
import './index.css'

export default class Header extends Component {

  // 对接收的props进行类型和必要性的限制
  static propTypes = {
    addTodo: PropTypes.func.isRequired
  }

  // 键盘事件回调
  handleKeyUp = (event) => {
    // 回车keyCode=13
    if (event.keyCode !== 13) {
      return
    }
    // 去掉空格
    if (!event.target.value.trim()) {
      return
    }
    this.props.addTodo( {
      id: nanoid(),
      name: event.target.value,
      done: false
    })
    event.target.value = ''
  }

  render() {
    return (
      <div className="todo-header">
        <input type="text" onKeyUp={this.handleKeyUp} placeholder="请输入你的任务名称，按回车键确认"/>
      </div>
    )
  }
}
